<?php

namespace App\Http\Controllers\Domain;

use App\Http\Controllers\Controller;
use App\Models\Player;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Models\Server;
use App\Helper;
use App\Models\Account;
use Illuminate\Support\Facades\Redirect;
use App\Models\Character;
use App\Http\Requests\PlayerChangePwdRequest;
use App\Events\PayEvent;
use Pay;
use App\Events\PlayerMoneyChangeEvent;
use App\Models\PlayerMoneyLog;

class UserController extends Controller
{
    public $prefix='domain';

    public function changePwd($domain){
        $server=Server::where('domain',$domain)->first();
        return view($this->prefix.'.user.changePwd',compact('server'));
    }

    public function changePwddo(PlayerChangePwdRequest $request,$domain){
        $server=Server::where('domain',$domain)->first();
        Helper::setDataBaseConf('mysql_auth',$server,'acore_auth');

        $user=json_decode(session('player'));

        $acc=Account::find($user->id);

        if (!$server->isOld()){
            $verifier=Account::getVerifier($acc->username,$request->get('password_old'),$acc->salt);
            if ($acc->verifier!=$verifier)
            {
                return Redirect::back()->with('msg','密码错误');
            }
            $acc->salt=Account::generateSalt();
            $acc->verifier=Account::getVerifier($acc->username,$request->get('password'),$acc->salt);
        }else{
            $pwd=sha1(strtoupper($acc->username).':'.strtoupper($request->get('password_old')));
            if ($acc->sha_pass_hash != strtoupper($pwd))
            {
                return Redirect::back()->with('msg','原密码错误');
            }

            $acc->sha_pass_hash=strtoupper(sha1(strtoupper($acc->username).':'.strtoupper($request->get('password'))));
            $acc->v='';
        }
        $acc->save();

        //判断是否是通讯GM账户，如果是，同步修改服务器GM账户密码
        if ($server->soap_acc===$acc->username){
            $server->soap_pwd=$request->get('password');
            $server->save();
        }

        return Redirect::back()->with('msg','修改成功，请牢记您的新密码，并使用新密码登陆游戏！');

    }

    public function center($domain){
        return redirect('/user/characters');
        $server=Server::where('domain',$domain)->first();
        Helper::setDataBaseConf('mysql_char',$server,'acore_characters');

        $acc_id=json_decode( session('player'))->id;

        $characters=Character::where('account',$acc_id)->orderBy('logout_time','desc')->get();

        return view($this->prefix.'.user.center',compact('server','characters'));
    }

    public function characters($domain){
        $server=Server::where('domain',$domain)->first();
        return view($this->prefix.'.user.characters',compact('server'));
    }
    public function getCharacters($domain){
        $server=Server::where('domain',$domain)->first();
        Helper::setDataBaseConf('mysql_char',$server,'acore_characters');
        $acc_id=json_decode( session('player'))->id;
        $characters=Character::where('account',$acc_id)->orderBy('logout_time','desc')->get();
        return JsonResponse::create(['err'=>0,'data'=>$characters]);
    }

    /**
     * [levelUp 角色升级页面]
     * @Author   Wuhaojie
     * @DateTime 2019-10-26T14:13:11+0800
     * @return   [type]                   [description]
     */
    public function levelUp($domain,$guid)
    {
        $server = Server::where('domain',$domain)->first();
        Helper::setDataBaseConf('mysql_char',$server,'acore_characters');
        $character = Character::find($guid);
    	return view($this->prefix.'.user.levelUp',compact('server','character'));
    }

    /**
     * [levelUpDo 升级订单]
     * @Author   Wuhaojie
     * @DateTime 2019-10-26T15:16:37+0800
     * @return   [type]                   [description]
     */
    public function levelUpDo(Request $request)
    {
    	// 支付请求
    	$level = $request->input('level'); //原始等级
    	$desLevel = $request->input('desLevel'); //目标等级
    	$type = $request->input('type') ?? 2;
        $server_id = $request->input('server_id');
        $manager_id = $request->input('user_id');
        $characterId = $request->input('character_id');
        $character_name = $request->input('character_name');
    	if (!isset($level) || !isset($desLevel) || !isset($type) || !isset($server_id) || !isset($manager_id) || !isset($characterId) || !isset($character_name)) {
    		return back()->with('msg','参数缺失');
    	}
    	if (!is_numeric($level) || !is_numeric($desLevel) || $level < 0 || $desLevel < 0) {
    		return back()->with('msg','非法参数');
    	}
    	$total_price = ($desLevel - $level) * config('conf.serverDef.moneyForPerLevel');
    	if ($total_price < 0) {
    		return back()->with('msg','非法请求');
    	}
    	$player_id = session('player')->id;
        $server = Server::find($server_id);
        // 我的余额
        Helper::setDataBaseConf('mysql_auth',$server,'acore_auth');
        $player = Account::find($player_id);
        $money = $player->money;
        if ($money < $total_price) {
            return back()->with('msg','您的积分不足,请购买积分');
        }
        $player->money -= $total_price;
        $player->save();
        // 客户加积分
        // $manager = User::find($manager_id);
        // $manager->remain_money += $total_price;
        // $manager->save();
        // 记录客户、用户积分记录
        // event(new ManagerMoneyChangeEvent($manager_id,$server_id,$player_id,3,1,$total_price,0,$manager->remain_money,'玩家'.$player->username.'使用'.$total_price.'积分将角色“'.$character_name.'”从等级'.$level.'升至等级'.$desLevel));
        event(new PlayerMoneyChangeEvent($manager_id,$server_id,$player_id,1,2,$total_price,0,$player->money,'使用'.$total_price.'积分将角色“'.$character_name.'”从等级'.$level.'升至等级'.$desLevel));
        return back()->with('msg','购买升级服务成功，请检查游戏内等级是否升级，如未正常升级，请联系管理员');
    }

    // 调起支付宝支付
    public function aliPayOrder($orderNum,$total_price,$subject)
    {
    	$order = [
		    'out_trade_no' => $orderNum,
		    'total_amount' => $total_price,
		    'subject' => $subject,
//            'return_url' => 'http://'.$domain.'.'.env('DOMAIN_PLAYER').'/user/moneyLog',
		];
		return Pay::alipay()->web($order);
    }

    // 调起微信支付
    public function wechatPayOrder($orderNum,$total_price,$subject)
    {
        $order = [
            'out_trade_no' => $orderNum,                 // 订单号
            'total_fee' => $total_price * 100,                 // 订单金额，单位：元
            'body' => $subject,   // 订单商品标题
        ];
        return Pay::wechat()->scan($order);
    }

    /**
     * [recharge 充值]
     * @Author   W
     * @DateTime 2020-10-23T09:06:06+0800
     * @param    Request                  $request [description]
     * @return   [type]                            [description]
     */
    public function recharge($domain,Request $request)
    {
        $server = Server::where('domain',$domain)->first();
        return view('domain.user.recharge',compact('server'));
    }

    public function rechargeDo(Request $request)
    {
        $data = $request->all();
        $player_id = session('player')->id;
        $order_num = 'wowP'.time().$player_id;
        $type = 3;//充值余额
        $subject = "WOW玩家充值";
        event(new PayEvent($data['manager_id'],$data['server_id'],$player_id,$order_num,$type,$data['money'],$data['pay_way'],0,$subject,''));
        if ($data['pay_way'] == 2) {
            // 支付宝
            $aliPay = $this->aliPayOrder($order_num,$data['money'],$subject);
            return $aliPay;
        } elseif ($data['pay_way'] == 1) {
            // 微信支付
            $wechatPay = $this->wechatPayOrder($order_num,$data['money'],$subject);
            $data['qrcode'] = $wechatPay['code_url'];
            $data['order_num'] = $order_num;
            return view('manager.wxPaySuccess',compact('data'));
        }

    }

    public function payForLevel($domain,Request $request){
        $server = Server::where('domain',$domain)->first();
        $guid=$request->get('guid');
        $toLevel=$request->get('toLevel');

        Helper::setDataBaseConf('mysql_char',$server,'acore_characters');
        $character = Character::find($guid);

        // 余额
        Helper::setDataBaseConf('mysql_auth',$server,'acore_auth');
        $account =Account::find(session('player')->id);
        $player=$account->getPlayer($server->id);

        $price=($toLevel-$character->level)*$server->ext['moneyForPerLevel'];

        if ($character->account != $account->id){
            return JsonResponse::create(['err'=>1,'msg'=>'非法请求']);
        }

        if ($character->level >= $server->ext['payforlevelMax']){
            return JsonResponse::create(['err'=>1,'msg'=>'此角色已经是最高等级']);
        }

        if ($player->money < $price){
            return JsonResponse::create(['err'=>1,'msg'=>'积分不足']);
        }

//        if ($character->online == 1){
//            return JsonResponse::create(['err'=>1,'msg'=>'角色在线中,请退出角色,再操作']);
//        }


        $player->money-=$price;
//        $character->level=$toLevel;
        $res='';
        $err='';
        $command="character level {$character->name} $toLevel";
        $server->RunCommand($command,$res,$err);
        $server->RunCommand("saveall",$res,$err);
        $player->save();
//        $character->save();
//        event(new PlayerMoneyChangeEvent($server->user_id,$server->id,$acc_id,2,2,$price,0,$player->money,'使用'.$price.'积分购买道具',$goodsId));
        event(new PlayerMoneyChangeEvent($server->user_id,$server->id,$account->id,1,2,$price,0,$player->money,'使用'.$price.'积分将角色等级“'.$character->name.'”从'.$character->level.'升至'.$toLevel));

        return JsonResponse::create(['err'=>0,'data'=>$account->money]);
    }

    public function timeToMoney($domain,Request $request)
    {
        $guid=$request->get('guid');
        $count=$request->get('count');

        $server = Server::where('domain',$domain)->first();

        $price=$count*$server->ext['timetomoneyRatio'];
        Helper::setDataBaseConf('mysql_char',$server,'acore_characters');
        $character = Character::find($guid);
        // 余额
        Helper::setDataBaseConf('mysql_auth',$server,'acore_auth');
        $account =Account::find(session('player')->id);

        if ($character->account != $account->id){
            return JsonResponse::create(['err'=>1,'msg'=>'非法请求']);
        }

        if ($character->online == 1){
            return JsonResponse::create(['err'=>1,'msg'=>'角色在线中,请退出角色,再操作']);
        }

        if ($character->totaltime < $price*60){
            return JsonResponse::create(['err'=>1,'msg'=>'游戏时间不足']);
        }

        if ($server->ext['timetoscore']==='1'){
            $player=Player::where('server_id',$server->id)->where('acc',$account->username)->first();
            if ($player){
                $player->money+=$count;
                $player->save();
                $character->totaltime -= $price*60;
                $character->save();
                return JsonResponse::create(['err'=>0,'data'=>$character->totaltime]);
            }else{
                return JsonResponse::create(['err'=>1,'msg'=>'no player']);
            }
        }else{
            //游戏内发放金币
            $res='';
            $err='';
            $character->SendMoney($server,'游戏时间兑换金币','感谢您的支持!',$count*10000,$res,$err);
            if ($err) {
                return JsonResponse::create(['err'=>1,'msg'=>$err]);
            }else{
                $character->totaltime -= $price*60;
                $character->save();
                return JsonResponse::create(['err'=>0,'data'=>$character->totaltime]);
            }
        }


    }

    /**
     * moneyLog 积分记录
     *
     * @param Request $request
     * @return void
     */
    public function moneyLog($domain,Request $request)
    {
        $server = Server::where('domain',$domain)->first();
        $data = $request->all();
        $trade_type = $data['trade_type'] ?? '';
        $list = PlayerMoneyLog::when($trade_type, function ($query) use ($trade_type) {
            return $query->where('trade_type',$trade_type);
        })->where('server_id',$server->id)
        ->where('player_id',session('player')->id)
        ->orderBy('created_at','desc')->paginate(10);
        return view('domain.user.money_log',compact('list','trade_type','server'));
    }
}
